<link rel="stylesheet" type="text/css" href="../css/alert.css">
<meta charset="UTF-8"/>
<?php

if (!init()) {
  redirect('?action=login');
}

include_once("functions/utils/ImageUtil.php");
$uploaddir = getcwd() . \controller\Config::getPropertyByKey('directory.gallery.image') . $_SESSION['id'] . "/";

$acceptedFormats = array('gif', 'png', 'jpg', 'jpeg');


$link_id = connectDB();

startTransaction();

$resultSet = null;


if (isset($_FILES['image']['name'])) {

  $uploadfile = '';
  if (in_array(strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)), $acceptedFormats)) {
    if (!file_exists($uploaddir)) {
      mkdir($uploaddir);
    }

    $fileExt = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);

    $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_gal_img" . "." . $fileExt;
    $uploadfile = $uploaddir . $file;


    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
      \util\ImageUtil::createImagePreview($uploadfile, 300, 'preview/gallery_preview', 'gallery');
      $timeStamp = getLocalTimeStamp();
      $date = f_Date($timeStamp);
      $time = f_Time($timeStamp);
      $resultSet = mysql_query("INSERT INTO gallery (userid, comment, date, time, header, path)
VALUES (" . $_SESSION['id'] . ",
        '" . mysql_real_escape_string($_POST['legend']) . "',
        '" . mysql_real_escape_string($date) . "',
        '" . mysql_real_escape_string($time) . "',
        '" . mysql_real_escape_string($_POST['header']) . "',
        '" . $_SESSION['id'] . "/" . $file . "')") or die(mysql_error());


//      if ($_POST['galvis'] == "true") {

      $tmpResultSet = mysql_query("SELECT id FROM groups WHERE groups.header = 'Base'") or die(mysql_error());
      $baseGroupRow = mysql_fetch_assoc($tmpResultSet);
      $imgInsertResult = mysql_query("INSERT INTO gallerygroups(galid, groupid, userid)
                VALUES ((SELECT id FROM gallery WHERE date = '" . $date . "' and time = '" . $time . "'),
                        '" . $baseGroupRow['id'] . "',
                        '" . $_SESSION['id'] . "')") or die(mysql_error());
//      }


    }

  }

}

$initiatorAction = \controller\ControllerUtil::getEncodedActionFromUrlWithParameters($_SERVER['HTTP_REFERER']);

if ($resultSet) {
  commitTransaction();
  redirect("?action=msg&header=header.galimg.success&body=body.galimg.success&view=" . $initiatorAction);
} else {
  rollbackTransaction();
  redirect("?action=msg&header=header.galimg.failed&body=body.galimg.failed&view=" . $initiatorAction);
}